"""
---------------------------------------------------------------------
- File: session.py
- Date: 2025/11/5
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 数据库引擎和会话工厂
---------------------------------------------------------------------
"""
from typing import cast

from sqlalchemy.orm.session import sessionmaker
from app.core.config import settings
from sqlalchemy.engine import Engine
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine

if "sqlite" in settings.ASYNC_DATABASE_URL:
    # 禁用sqlite的线程检查
    connect_args = {"check_same_thread": False}
else:
    connect_args = {}

# 1. 创建异步引擎
async_engine = create_async_engine(
    settings.ASYNC_DATABASE_URL,  # 数据库连接字符串
    echo=settings.DEBUG,          # 打印sql语句
    connect_args=connect_args,    # 数据库连接参数
    future=True,                  # 启用异步模式
)

# 2. 创建异步会话工厂（AsyncSession）
AsyncSessionLocal = sessionmaker(
    autocommit=False,                # 关闭自动提交
    autoflush=False,                 # 关闭自动刷新
    bind=cast(Engine, async_engine), # 使用cast类型检查器，将async_engine视为Engine类型，
    class_=AsyncSession,             # 指定使用异步会话
    expire_on_commit=False,          # 关闭会话提交时过期失效
)
